package org.common.convert.tohtml;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.common.convert.util.FileHelper;
import org.common.convert.util.HtmlCharsetFixer;
import org.common.convert.util.HtmlImageToDataUri;
import org.common.convert.util.RandomStringGenerator;
import org.w3c.dom.Document;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;

/**
 * 将doc转为html
 */
public class DocToHtml {
    /**
     * 将doc转为html
     * @param inputFilePath  源doc路径
     * @param outputFilePath 输出html路径
     * @throws Exception
     */
    public static void wordToHtml(String inputFilePath, String outputFilePath) throws Exception {
        InputStream is = new FileInputStream(inputFilePath);
//        InputStream is = FileHelper.convertWordToUTF8Stream(inputFilePath);
        System.out.println("outputFilePath:"+outputFilePath);
        HWPFDocument wordDocument = new HWPFDocument(is);
        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());

        String rootPath = FileHelper.getPath(outputFilePath);

        wordToHtmlConverter.setPicturesManager(new PicturesManager() {

            @Override
            public String savePicture(byte[] bytes, PictureType pictureType, String s, float v, float v1) {
                String shortFileName  = RandomStringGenerator.generateRandomString(10);
                File file = null;
                while(true) {
                    file = new File(rootPath + shortFileName + ".png");
                    if(!file.exists()){
                        break;
                    }
                }
                try {
                    FileOutputStream out = new FileOutputStream(file);
                    out.write(bytes);
                    out.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return shortFileName+".png"; // 返回图片的相对路径或者URL
            }


        });
        wordToHtmlConverter.processDocument(wordDocument);
        Document htmlDocument = wordToHtmlConverter.getDocument();

        // 将Document转换为XHTML
        StringWriter writer = new StringWriter();
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        transformer.setOutputProperty(OutputKeys.METHOD, "html");
        transformer.transform(new DOMSource(htmlDocument), new StreamResult(writer));

        // 输出 HTML 字符串
        String htmlString = writer.getBuffer().toString();
        // 将 HTML 字符串写入文件
        FileOutputStream out = new FileOutputStream(outputFilePath);
        byte[] bytes = htmlString.getBytes("UTF-8");
        out.write(bytes);
        out.close();
        //将html文件中的图片转为datauri格式
        HtmlImageToDataUri.convertImgToDataUri(outputFilePath, outputFilePath);
        //修复html文件中的编码问题
        HtmlCharsetFixer.fixCharsetMeta(outputFilePath, outputFilePath);
    }
    public static void main(String[] args) {
        try {
            wordToHtml("中交电商公司党支部召开组织生活会V0.3-新闻稿.doc", "中交电商公司党支部召开组织生活会V0.3-新闻稿.html");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
